package shell.listener;

import inabit.base.RuleBase;
import inabit.base.WorkingMemory;
import inabit.inabitcompiler.compiler.InabitCompiler;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import shell.view.windows.InabitWindow;
/**@author Rafael Rocha*/
public class OpenFileListener implements ActionListener {

	private InabitWindow window;

	public OpenFileListener(InabitWindow window) {
		this.window = window;
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		JFileChooser fc = new JFileChooser();
		int option = fc.showOpenDialog(window);

		if (option == JFileChooser.APPROVE_OPTION) {
			File f = fc.getSelectedFile();
			InabitCompiler compiler = new InabitCompiler();
			try {
				compiler.compileFromFile(f);
				WorkingMemory wm = window.getWorkingMemory();
				RuleBase rb = window.getRuleBase();

				wm.removeAll(window.getWorkingMemory().getVariables());
				wm.addVariables(compiler.getCompiledVariables());

				rb.removeRules(rb.getRules());
				rb.addRulesWithModusTollens(compiler.getCompiledRules());

				window.update();
				window.repaint();
			} catch (Exception e) {
				e.printStackTrace();
				JOptionPane.showMessageDialog(window, e.getMessage(),
						"Erro ao compilar base de dados ",
						JOptionPane.ERROR_MESSAGE);
			}

		}
	}

}
